import json
from utils.logger import logger

class APIAssertion:
    """
    API断言工具类，提供常用的断言方法
    """
    @staticmethod
    def assert_status_code(response, expected_code=200):
        """
        断言响应状态码
        :param response: 响应对象
        :param expected_code: 预期状态码
        """
        assert response.status_code == expected_code, \
            f"期望状态码 {expected_code}，实际状态码 {response.status_code}，响应内容: {response.text}"
    
    @staticmethod
    def assert_json_key(response, key):
        """
        断言JSON响应包含指定键
        :param response: 响应对象
        :param key: 键名
        """
        try:
            json_data = response.json()
            assert key in json_data, f"响应中未找到键 '{key}'"
        except json.JSONDecodeError:
            assert False, f"响应不是有效的JSON格式: {response.text}"
    
    @staticmethod
    def assert_json_value(response, key, expected_value):
        """
        断言JSON响应中指定键的值
        :param response: 响应对象
        :param key: 键名
        :param expected_value: 预期值
        """
        try:
            json_data = response.json()
            assert key in json_data, f"响应中未找到键 '{key}'"
            assert json_data[key] == expected_value, \
                f"键 '{key}' 的值不匹配，期望 {expected_value}，实际 {json_data[key]}"
        except json.JSONDecodeError:
            assert False, f"响应不是有效的JSON格式: {response.text}"
    
    @staticmethod
    def assert_json_structure(response, expected_keys):
        """
        断言JSON响应结构包含预期的所有键
        :param response: 响应对象
        :param expected_keys: 预期键列表
        """
        try:
            json_data = response.json()
            for key in expected_keys:
                assert key in json_data, f"响应中未找到键 '{key}'"
        except json.JSONDecodeError:
            assert False, f"响应不是有效的JSON格式: {response.text}"